package org.brownflat.lighthouse.ci.pulse;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.brownflat.lighthouse.ci.Build;
import org.brownflat.lighthouse.ci.Builder;
import org.brownflat.lighthouse.ci.Feed;
import org.brownflat.lighthouse.xml.XMLDocument;

public class PulseBuilder implements Builder<Feed, String> {

	@Override
	public Feed build(String input) {
		XMLDocument document = new XMLDocument(input);
		Feed feed = new Feed();
		List<XMLDocument> builds = document.documentsAt("/rss/channel/item");
		
		Pattern pattern = Pattern.compile("Project (.*) (build \\d) (succeeded|failed)");
		
		for (Iterator iterator = builds.iterator(); iterator.hasNext();) {
			XMLDocument thisBuild = (XMLDocument) iterator.next();
			Build build = new Build();
			String title = thisBuild.selectValueAt("/item/title");
			build.setBroken(title.contains("failed"));
			Matcher matcher = pattern.matcher(title);
			if(matcher.matches()) {
				build.setProject(matcher.group(1));
			} else {
				throw new RuntimeException("Could not determine build name from " + title);
			}
			build.setDate(getDate(thisBuild.selectValueAt("/item/pubDate")));
			feed.addBuild(build);
		}
		
		return feed;
	}
	
	private Date getDate(String date) {
		try {
			return new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z").parse(date);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}
}
